//mysqlConfig.js
var mysql = require('mysql');
var config = require('./defaultConfig');

var pool = mysql.createPool({
    host: config.database.HOST,
    user: config.database.user,
    password: config.database.pwd,
    database: config.database.database
});

let allServices = {
    query: function (sql, values) {
        
        return new Promise((resolve, reject) => {
            pool.getConnection(function (err, connection) {
                if (err) {
                    reject(err)
                } else {
                    connection.query(sql, values, (err, rows) => {
                        if (err) {
                            reject(err)
                        } else {
                            resolve(rows)
                        }
                        connection.release()
                    })
                }
            })
        })

    },
   findUserData: function () {
        let _sql = `select * from users ;`
        return allServices.query(_sql)
    },
    addUserData: (obj) => {
         let _sql = "insert into users set username=?,password=?;"
         return allServices.query(_sql, obj)
     },
     login:()=>{ 
        let _sql = `select * from users `
         return allServices.query(_sql)
     },
     getMsgData:()=>{
        let _sql = `select * from message ;`
        return allServices.query(_sql)
     },
     upPwd:(obj)=>{
        let _sql =  `update users set password="${obj.password}" where username="${obj.username}"`; 
        console.log(_sql,"==================")
        return allServices.query(_sql)
     },
     addRegist:(obj)=>{
         let arr=JSON.stringify( Object.values(obj))
         let _sql = `insert into users (${Object.keys(obj).toString()}) VALUES (${ arr.substring(1,arr.length-1)})`
        return allServices.query(_sql)
     },
}


module.exports = allServices;